package com.hmall.trade.listener;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.domain.MultiDelayMessage;
import com.hmall.trade.constants.TradeMqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@RequiredArgsConstructor
public class OrderStatusListener {
    private final RabbitTemplate rabbitTemplate;
    private final IOrderService orderService;
    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = TradeMqConstants.DELAY_ORDER_QUEUE, durable = "true"),
            exchange = @Exchange(value = TradeMqConstants.DELAY_EXCHANGE, type = ExchangeTypes.TOPIC, delayed = "true",
            durable = "true"),
            key = TradeMqConstants.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenOrderStatus(MultiDelayMessage<Long> message) {
        // 1. 查询订单状态
        Long orderId = message.getData();
        Order order = orderService.getById(orderId);
        //2. 如果订单不存在或者订单状态不是未支付，则返回
        if (order == null || order.getStatus() > 1) {
            return;
        }
        //3. 如果订单存在且状态是未支付，则调用PayClient查询支付状态
        PayOrderDTO payOrderDTO = payClient.queryPayOrderDTOByBizOrderNo(orderId);
        //3.1 如果支付单状态是已支付，则更新订单状态
        if (payOrderDTO != null && payOrderDTO.getStatus() == 3) {
            orderService.markOrderPaySuccess(orderId);
            return;
        }
        //3.2 如果还有剩余延迟时间，则发送下一个延迟消息
        if (message.hasNextDelay()) {
            Integer delayMillis = message.removeNextDelay();
            rabbitTemplate.convertAndSend(TradeMqConstants.DELAY_EXCHANGE, TradeMqConstants.DELAY_ORDER_ROUTING_KEY, message,
                    message1 -> {
                        message1.getMessageProperties().setDelay(delayMillis);
                        return message1;
                    });
            return;
        }
        //4. 如果支付单状态是未支付,则取消订单
        orderService.cancelOrder(orderId);
    }
}
